package 力扣面试经典150;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2024-03-21
 * Time:17:16
 */

/**
 * 力扣面试经典150:61. 旋转链表
 * 已解答
 * 中等
 * 相关标签
 * 相关企业
 * 给你一个链表的头节点 head ，旋转链表，将链表每个节点向右移动 k 个位置。
 * 示例 1：
 * 输入：head = [1,2,3,4,5], k = 2
 * 输出：[4,5,1,2,3]
 * 示例 2：
 * 输入：head = [0,1,2], k = 4
 * 输出：[2,0,1]
 */
public class rotateRight {
    public static ListNode createLinkedList(int[] nodes) {
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;
        for (int node : nodes) {
            current.next = new ListNode(node);
            current = current.next;
        }
        return dummy.next;
    }
    public static void main(String[] args) {
        int[] nodes = {1, 2, 3, 4, 5};
        ListNode head = createLinkedList(nodes);
        rotateRight(head,2);
    }
    public static ListNode rotateRight(ListNode head, int k) {
        if(head == null || k == 0) return head;

        ListNode cur = head;
        int count = 1;
        while(cur.next != null){
            cur = cur.next;
            count++;
        }
        cur.next = head;

        k = k % count;
        for (int i = 0; i < count - k; i++) {
            cur = cur.next;
        }

        head = cur.next;
        cur.next = null;

        return head;
    }
}
